<template>
  <div class="fawen">
    <el-dialog
      title="批示意见/办理提示"
      :visible.sync="dialogVisible"
      width="60%">
      <notice :noticePersonId="noticePersonId" :step="selStep"></notice>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="录入领导批示"
      :visible.sync="leaderOpinionDialogVisible"
      width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
        <el-form
          ref="form"
          label-width="150px"
          label-position="right">
          <el-form-item label="部领导批示">
            <leaderOpinion :recordId="leaderOpinionId" recordTable="bus_post_dispatch_batch" :leaderType="1" :canEdit="true"></leaderOpinion>
          </el-form-item>
          <el-form-item label="司领导批示">
            <leaderOpinion :recordId="leaderOpinionId" recordTable="bus_post_dispatch_batch" :leaderType="2" :canEdit="true"></leaderOpinion>
          </el-form-item>
          <el-form-item>
            <el-button type="success" class="marginT10" @click="leaderOpinionDialogVisible=false">关闭</el-button>
          </el-form-item>
        </el-form>
    </el-dialog>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/selection' }">干部选任</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/selection/fawen' }">任职发文</el-breadcrumb-item>
    </el-breadcrumb>
    <section class="wboxnoborder">
      <div :style="'height:'+tableHeight+'px'">
        <el-scrollbar style="height: calc(100% + 16px);">
          <el-tabs v-model="activeName" type="card" @tab-click="tabsClick" style="margin:15px">
            <el-tab-pane label="待办理" name="first">
              <span slot="label" v-if="countnum1>0" class="pointtab"><el-badge :value="countnum1" class="item">待办理</el-badge></span>
                <el-table
                  v-loading="loading1"
                  border
                  size="small"
                  :data="tableData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="handleSelectionChange">
                  <el-table-column
                    type="selection"
                    width="55">
                  </el-table-column>
                  <el-table-column
                    label="序号"
                    type="index"
                    width="50">
                  </el-table-column>
                  <el-table-column
                    prop="realName"
                    label="姓名"
                    width="150">
                  </el-table-column>
                  <el-table-column
                    prop="unitName"
                    label="选任岗位单位"
                    show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column
                    prop="jobName"
                    width="250"
                    label="选任岗位职务"
                    show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column
                    prop="jobLevel"
                    label="选任岗位职级"
                    width="150"
                    show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column
                    label="办理提示、批示意见"
                    width="150">
                    <template slot-scope="scope">
                      <el-popover placement="bottom" width="600" trigger="hover">
                        <notice :noticePersonId="scope.row.personId" step="8"></notice>
                        <el-button size="small" slot="reference" type="primary" @click="showNotice(scope.row.personId)">查看详情</el-button>
                      </el-popover>
                      <!-- <el-button @click="showNotice(scope.row.personId)" type="primary" size="small">查看详情</el-button> -->
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="任职时间"
                    width="200">
                    <template slot-scope="scope">
                      <el-date-picker
                        v-model="scope.row.date"
                        type="date"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                        style="width:170px;">
                      </el-date-picker>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="是否有试用期"
                    width="220">
                    <template slot-scope="scope">
                      <el-radio-group v-model="scope.row.radio">
                        <el-radio :label="1">是</el-radio>
                        <el-radio :label="0">否</el-radio>
                      </el-radio-group>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button class="marginT10" type="primary" @click="fawenClick" :loading="submitloading1">任职发文</el-button>
            </el-tab-pane>
            <el-tab-pane label="正在办理" name="second">
              <span slot="label" v-if="countnum2>0" class="pointtab"><el-badge :value="countnum2" class="item">正在办理</el-badge></span>
              <el-table
                border
                v-loading="loading2"
                size="small"
                ref="multipleTable"
                :data="tableData2"
                tooltip-effect="dark"
                style="width: 100%">
                <el-table-column
                  label="序号"
                  type="index"
                  width="50">
                </el-table-column>
                <el-table-column
                  prop="names"
                  label="人选"
                  show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  label="任职文号"
                  width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.input" placeholder="请输入任职文号"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  label="领导批示"
                  width="200">
                  <template slot-scope="scope">
                    <el-button @click="leaderOpinion(scope.row.id)" type="primary" size="small">录入领导批示</el-button>
                  </template>
                </el-table-column>
                <el-table-column
                  label="附件"
                  width="200">
                  <template slot-scope="scope">
                    <el-upload
                      class="upload-demo"
                      :on-success="function (res, file) { return getImportList(res, file, scope.$index)}"
                      :on-remove="handleRemove"
                      :before-remove="beforeRemove"
                      :on-error='uploadError'
                      :action="$http.defaults.baseURL + $http.defaults.selectionAPI + 'api/gen/file/upload/'"
                      :file-list="scope.row.fileList"
                      with-credentials
                      >
                      <el-button type="primary" size="small">点击上传</el-button>
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="480">
                  <template slot-scope="scope">
                    <el-button @click="exportfwmb(scope.row)" type="primary" size="small">导出发文模板</el-button>
                    <el-button @click="finishBL(scope.row)" type="success" size="small">办理完成并发送给干部处处长</el-button>
                    <el-button @click="delBL(scope.row)" type="danger" size="small" class="marginL8">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-scrollbar>
      </div>
    </section>
  </div>
</template>

<script>
import notice from '../common/Notice'
import leaderOpinion from '../common/leaderOpinion'
export default {
  name: 'fawen',
  components: {
    notice, leaderOpinion
  },
  data () {
    return {
      leaderOpinionId: '',
      leaderOpinionDialogVisible: false,
      countnum1: 0,
      countnum2: 0,
      loading1: false,
      loading2: false,
      submitloading1: false,
      submitloading2: false,
      tableHeight: 100,
      activeName: 'first',
      tableData: [],
      tableData2: [],
      fawenPersons: [], // 代办理表格 table select change
      files: [],
      fileList: [], // 任职发文 办理中 上传附件
      selectData: {
        hjData: [
        ],
        szData: [
        ],
        cnData: [
        ],
        yyData: []
      },
      selectPerson: [], // 待批示
      selectPerson2: [], // 已批示
      selApi: 'api/selection/postdispatch/submitApprove',
      selStep: 8,
      noticePersonId: '', // notice persion id
      dialogVisible: false // 已批示
    }
  },
  methods: {
    getImportList (res, file, index) {
      if (res.success) {
        this.$message({
          message: '上传成功！' + res.message,
          type: 'success'
        })
        console.log('index')
        console.log(index)
        this.tableData2[index].files.push(res.result[0])
      } else {
        console.log(res.message)
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    exportfwmb (data) {
      if (data.input) {
        let para = {batchId: data.id, docno: data.input}
        let url = this.$http.defaults.selectionAPI + 'api/selection/document/exportRmztz'
        // console.log(url)
        this.$http.post(url, para).then(res => {
          if (res.data.success === true) {
            this.download(res.data.result)
          } else {
            this.$message({
              message: '数据获取失败',
              type: 'error'
            })
          }
        })
      } else {
        this.$message({
          message: '请输入任职文号',
          type: 'error'
        })
      }
    },
    download (fileid) {
      var downloadElement = document.createElement('a')
      downloadElement.href = this.$http.defaults.baseURL + this.$http.defaults.selectionAPI + 'api/gen/file/download?id=' + fileid
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
    },
    leaderOpinion (id) {
      this.leaderOpinionId = id
      this.leaderOpinionDialogVisible = true
    },
    getNum () {
      let url = this.$http.defaults.selectionAPI + 'api/selection/statnum/postdispatch/getStatNum'
      // console.log(url)
      this.$http.get(url).then(res => {
        if (res.data.success === true) {
          this.countnum1 = res.data.result.countnum4 // 处内人员的countnum1对应处长的countnum4
          this.countnum2 = res.data.result.countnum2
        } else {
          this.$message({
            message: '数据获取失败',
            type: 'error'
          })
        }
      })
    },
    saveComplete () {
      if (this.selectPerson2.length === 0) {
        this.$message({
          message: '请至少选择一个人选',
          type: 'error'
        })
        return
      }
      let url = this.$http.defaults.selectionAPI + this.selApi
      let arr = []
      for (let i of this.selectPerson2) {
        arr.push({
          id: i.personId,
          arrivalTime: i.arrivalTime,
          probationPeriod: i.probationPeriod
        })
      }
      this.submitloading2 = true
      this.$http.post(url, {
        receiveUserId: -1,
        persons: arr,
        step: 8
      }).then(res => {
        this.submitloading2 = false
        if (res.data.success === true) {
          this.$message({
            message: '办理完成',
            type: 'success'
          })
          this.getList4()
        }
      })
    },
    loadSelectData1 () {
      this.selectData = {
        hjData: [
        ],
        szData: [
        ],
        cnData: [
        ],
        yyData: []
      }
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/auth/getUsersByRole?roletype=3`)
        .then(response => {
          if (response.data.success) {
            this.selectData.cnData = []
            for (let i = 0; i < response.data.result.length; i++) {
              this.selectData.cnData.push(response.data.result[i])
            }
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/home/getCommonlyOpinions?step=8`)
        .then(response => {
          if (response.data.success) {
            this.selectData.yyData = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    loadSelectData () {
      this.selectData = {
        hjData: [
        ],
        szData: [
        ],
        cnData: [
        ],
        yyData: []
      }
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/auth/getUsersByRole?roletype=2`)
        .then(response => {
          if (response.data.success) {
            this.selectData.szData = []
            for (let i = 0; i < response.data.result.length; i++) {
              if (response.data.result[i].roleName === 'ROLE_sizhang' || response.data.result[i].manageDep.indexOf(localStorage.getItem('unitName')) > -1) {
                this.selectData.szData.push(response.data.result[i])
              }
            }
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
      this.$http
        .get(this.$http.defaults.selectionAPI + `api/selection/home/getCommonlyOpinions?step=8`)
        .then(response => {
          if (response.data.success) {
            this.selectData.yyData = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    tabsClick (tab) {
      // console.log(tab)
      if (tab.name === 'first') {
        console.log('first in')
        this.getList()
      } else if (tab.name === 'second') {
        this.getList2()
      }
    },
    getList2 () {
      this.getNum()
      this.loading2 = true
      let url = this.$http.defaults.selectionAPI + 'api/selection/postdispatch/getProcessingBatchInfo'
      // console.log(url)
      this.$http.get(url, {}).then(res => {
        this.loading2 = false
        console.log('get list22 succ:', res)
        if (res.data.success === true) {
          let rs = res.data.result
          let arr = []
          for (let i of rs) {
            let brr = []
            for (let j of i.persons) {
              brr.push(j.realName)
            }
            arr.push({
              id: i.id,
              names: brr.join(' '),
              files: i.files,
              fileList: this.formatFiles(i.files),
              input: '',
              persons: i.persons
            })
          }
          this.tableData2 = arr
        } else {
          this.$message({
            message: '数据获取失败',
            type: 'error'
          })
        }
      })
    },
    getList () {
      this.getNum()
      this.loading1 = true
      let url = this.$http.defaults.selectionAPI + 'api/selection/postdispatch/getApprove'
      // console.log(url)
      this.$http.get(url, {}).then(res => {
        this.loading1 = false
        console.log('get list44 succ:', res)
        if (res.data.success === true) {
          let rs = res.data.result
          this.tableData = rs
        } else {
          this.$message({
            message: '数据获取失败',
            type: 'error'
          })
        }
      })
      this.loadSelectData()
    },
    formatFiles (files) {
      if (files && files.length > 0) {
        let newfiles = []
        for (let i = 0; i < files.length; i++) {
          newfiles.push({name: files[i].fileName + '.' + files[i].fileType, id: files[i].id})
        }
        return newfiles
      } else {
        return []
      }
    },
    handleSelectionChange (val) { // 任职发文 待办理
      console.log('tabledata val:', val)
      this.fawenPersons = [...val]
    },
    fawenClick () { // 发文 生成批次 按钮
      console.log('click fawen')
      if (this.fawenPersons && this.fawenPersons.length > 0) {
        let url = this.$http.defaults.selectionAPI + 'api/selection/postdispatch/saveBatchByPersons'
        console.log(this.fawenPersons)
        // 获取报备persons
        let arr = []
        for (let i of this.fawenPersons) {
          if (i.date === undefined || i.date === null || i.date === '') {
            this.$message({
              message: '每一个勾选的人都需要选择日期',
              type: 'warning'
            })
            return
          } else if (i.radio === undefined || i.radio === null || i.radio === '') {
            this.$message({
              message: '每一个勾选的人都需要选择试用期',
              type: 'warning'
            })
            return
          } else {
            arr.push({
              personId: i.personId,
              arrivalTime: i.date,
              probationPeriod: i.radio
            })
          }
        }
        this.submitloading1 = true
        this.$http.post(url, {
          persons: arr
        }).then(res => {
          this.submitloading1 = false
          console.log('发文 succ res:', res)
          if (res.data.success === true) {
            this.$message({
              message: '发文成功',
              type: 'success'
            })
            this.getList()
          }
        })
      } else {
        this.$message({
          message: '请至少选择一个人选',
          type: 'error'
        })
      }
    },
    handleUploadSucc (response, file, fileList) { // 任职发文 办理中 附件
      console.log(response)
      if (response.success) {
        this.files.push(response.result[0])
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    beforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
      let fid = file.response.result[0].id
      let url = this.$http.defaults.selectionAPI + 'api/gen/file/remove'
      this.$http.get(url, {
        params: {
          id: fid
        }
      }).then(res => {
        console.log('删除成功:', res)
        if (res.data.success === true) {
          let index = this.files.indexOf(fid)
          if (index !== -1) {
            this.files.splice(index, 1)
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
          }
        }
      })
    },
    uploadError (err) {
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    finishBL (item) { // 办理中 完成
      console.log('办理中 完成', item)
      if (item.input === '') {
        this.$message({
          message: '请填写任职文号',
          type: 'warning'
        })
        return
      }
      let url = this.$http.defaults.selectionAPI + 'api/selection/postdispatch/updateBatchComplete'
      console.log('files:', item.files)
      let arr = []
      for (let i of item.files) {
        arr.push(i.id)
      }
      this.$http.post(url, {
        postDispatchBatchId: item.id,
        docno: item.input,
        files: arr
      }).then(res => {
        console.log('办理中 完成:', res)
        if (res.data.success === true) {
          this.$message({
            message: '已办理完成并发送给干部处处长',
            type: 'success'
          })
          this.getList2()
        }
      })
    },
    delBL (item) { // 办理中 删除
      console.log('del', item)
      this.$confirm('是否删除待上会审议批次', '操作确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = this.$http.defaults.selectionAPI + 'api/selection/postdispatch/removeBatch'
        this.$http.get(url, {
          params: {
            postDispatchBatchId: item.id
          }
        }).then(res => {
          console.log('删除办理批次res:', res)
          if (res.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getList2()
          }
        })
      }).catch(() => {
        console.log('取消删除')
      })
    },
    showNotice (id) { // 已批示 批示意见
      console.log('show notice id:', id)
      this.noticePersonId = id
      this.dialogVisible = true
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - 165
      })
    }
  },
  mounted () {
    // let params = this.$route.params
    // console.log('讨论决定详情params:', params)
    // 代办理列表
    this.getList()
    // resize
    this.tableresize(this)
    let _this = this
    window.onresize = function windowResize () {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      _this.tableresize(_this)
    }
  }
}
</script>

<style>
.fawen .el-table--border td, .el-table--border th, .el-table__body-wrapper .el-table--border.is-scrolling-left~.el-table__fixed{
  border-bottom:1px solid #95B8E7;
}
.fawen .el-table td, .el-table th.is-leaf{
  border-right:1px solid #95B8E7;
}
.fawen .wboxnoborder .el-table{
  border: #95B8E7 solid 1px;
}
.fawen .wboxnoborder .el-table th{
  font-weight: normal;
  background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  text-align: center;
  border-right: #95B8E7 solid 1px;
  border-bottom: #95B8E7 solid 1px;
  min-height: 30px;
  line-height:30px;
}
.fawen .wboxnoborder .el-table td, .el-table th{
  padding:0;
  font-size:var(--size14) !important;
  line-height: 20px;
  font-family: '宋体';
  text-align: center;
}
.fawen .el-table__row{
  height: 50px;
}
</style>
<style scoped>
.fawen {
  width: 100%;
}
.fawen .wboxnoborder {
  padding: 0;
  width: 100%;
  background-color: #fff;
  margin: 0 10px;
  overflow: hidden;
}
</style>
